package com.atguigu.gmall.common.service;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RabbitService {

    //引入发送消息的模板
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 封装发送消息的方法
     * @param exchange   交换机
     * @param routingKey 路由键
     * @param msg        消息
     * @return
     */
    public boolean sendMsg(String exchange, String routingKey, Object msg) {
        //发送消息
        rabbitTemplate.convertAndSend(exchange, routingKey, msg);
        //默认返回
        return true;
    }

    /**
     * 发送延迟消息的方法.
     * @param exchange
     * @param routingKey
     * @param msg
     * @param delayTime
     * @return
     */
    public Boolean sendDelayMsg(String exchange, String routingKey, Object msg, int delayTime) {
        //  发送消息:
        this.rabbitTemplate.convertAndSend(exchange, routingKey, msg, message -> {
            //  设置一下延迟时间.
            message.getMessageProperties().setDelay(delayTime * 1000);
            return message;
        });
        //默认返回数据
        return true;
    }

}
